﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace THO7AlgoritmTimerApplication.Filters.Noise
{
    public class SaltAndPepper : Filter
    {
        private double _percentage;

        public SaltAndPepper(double percentage)
            : base()
        {
            _percentage = percentage;
        }

        public override Bitmap RunFilter()
        {
            Bitmap output = new Bitmap(_width, _height);
            BitmapData outputData = output.LockBits(new Rectangle(0, 0, _width, _height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            int totalWidth = _width * 3;
            int srcOffset = _sourceData.Stride - totalWidth;
            int optOffset = outputData.Stride - totalWidth;

            double pr = 1.0 - _percentage / 100.0;
            int count = 0;
            unsafe
            {
                byte* srcPnt = (byte*)_sourceData.Scan0;
                byte* optPnt = (byte*)outputData.Scan0;
                Random r = new Random();
                double random = 0.0;
                for (int y = 0; y < _height; y++)
                {
                    for (int x = 0; x < _width; x++)
                    {
                        random = 2.0 * (r.Next(32767) - 32767 / 2.0) / 32767;
                        if (random > pr)
                        {
                            optPnt[0] = 255;
                            optPnt[1] = 255;
                            optPnt[2] = 255;
                            ++count;
                        }
                        else if (random < -pr)
                        {
                            optPnt[0] = 0;
                            optPnt[1] = 0;
                            optPnt[2] = 0;
                            ++count;
                        }
                        else
                        {
                            optPnt[0] = srcPnt[0];
                            optPnt[1] = srcPnt[1];
                            optPnt[2] = srcPnt[2];
                        }
                        srcPnt += 3;
                        optPnt += 3;
                    }
                    srcPnt += srcOffset;
                    optPnt += optOffset;
                }
            }
            double actualpercent = 100.0 * count / (_width * _height);
            Console.WriteLine(actualpercent);
            output.UnlockBits(outputData);
            return output;
        }
    }
}
